import React from 'react';
import {Button} from 'antd';
import moment from "moment";
import ExportJsonExcel from "js-export-excel";

const DownExcel: React.FC<{}> = (
  {
    queryRule,
    columns,
  }: {
    queryRule?: ()=>{},
    columns?: [],
}) => {
  /**
   *  下载数据
   * @param
   */
  const handleDown = async (column:any) => {
    const option = {};
    const res = await queryRule({
      isDown: 1,
    });
    const columns = [];
    var i = 0;
    column.forEach(c => {
      if(c.hideInTable){
        return true;
      }else {
        if(c.children){
          c.children.forEach(d => {
            columns[i]=d;
            columns[i]['title']=c.title+d.title;
            i++;
          });
        }else {
          columns[i]=c;
          i++;
        }

      }

    });
    if(res.status === 'ok'){
      option.fileName = moment().startOf('day');
      option.datas = [
        {
          sheetData: res.data.map(item => {
            const result = {};
            columns.forEach(c => {
              if(c.children){
                c.children.forEach(d => {
                  if(d.valueEnum){
                    result[d.dataIndex] = d.valueEnum[item[d.dataIndex]];
                  }else {
                    if(!item[d.dataIndex]){
                      result[d.dataIndex] = 0;
                    }else{
                      if(d.valueType === 'percent'){
                        result[d.dataIndex] = item[d.dataIndex]+'%';
                      }else{
                        result[d.dataIndex] = item[d.dataIndex];
                      }
                    }
                  }
                });
              }else {
                if(c.valueEnum){
                  result[c.dataIndex] = c.valueEnum[item[c.dataIndex]];
                }else {
                  if(!item[c.dataIndex]){
                    result[c.dataIndex] = 0;
                  }else{
                    if(c.valueType === 'percent'){
                      result[c.dataIndex] = item[c.dataIndex]+'%';
                    }else{
                      result[c.dataIndex] = item[c.dataIndex];
                    }
                  }
                }
              }

            });
            return result;
          }),
          sheetName: 'ExcelName',     // Excel文件名称
          sheetFilter: columns.map(item => item.dataIndex),
          sheetHeader: columns.map(item => item.title),
          columnWidths: columns.map(() => 10),
        },
      ];
      const toExcel = new ExportJsonExcel(option);
      toExcel.saveExcel();
    }
  };

  return (
    <Button type="primary" onClick={async () => {
      await handleDown(columns)}} >导出</Button>

  );
};
export default DownExcel;
